# coding:utf-8
import os

from ckeditor.fields import RichTextField
from django.db.models.query import QuerySet
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from user.models import user
from models import stuchengji
from django.db.models import Avg, Max, Min, Sum, datetime
from django.contrib.auth.models import User
from django.views.decorators.csrf import  csrf_exempt

classlist = ["一班", "二班", "三班", "四班", "五班", "六班", "七班", "八班", "九班", "十班"]
grouplist = ["一年级", "二年级", "三年级"]
kecheng = ["语文", "英语", "数学", "历史", "物理", "体育", "政治", "化学", "音乐"]
context = {}


def classname(request):
     if request.method == 'GET':
        g = int(request.GET.get('g'))
        c = int(request.GET.get('c'))
        context["g"] = g
        context["c"] = c
        context["group"] = grouplist[g]
        context["class"] = classlist[c]
    # a={'grocla':group+classname}

        # numlist = user.objects.values("num").filter(group=g, classname=c)
        # alllist=stuchengji.objects.all()
        # alllist.query.group_by = ['kecheng']
        # context["alllist"]=alllist
        # avglist=stuchengji.objects.filter(num__in=numlist).aggregate(Avg('chuqin'),Avg('taidu'),Avg('zuoye'),Avg('ceyan'),Avg('danyuan'),Avg('qizhong'),Avg('qimo'))
        # context["avglist"] = avglist
     return render(request, "teacher/home.html", context)


def addstu(request):
    msg=0
    if request.method == 'POST':
        try:
            new,create = User.objects.get_or_create(
                # num=int(request.POST.get('xuehao')),
                username=request.POST.get('name'),
                is_superuser=0,
                password='pbkdf2_sha256$12000$b0CXkwBlfFBO$m77sIpQu2pORsN43lXkT554cT4rmDYK8ByQOG0Z0768=',
                email=request.POST.get('email'),
                is_staff=0,
                is_active=1
            )
        except:
            msg+=1
        try:
            user.objects.get_or_create(
                 id_card=int(request.POST.get('xuehao')),
                 name=request.POST.get('name'),
                group=context["g"],
                classname=context["c"],
                num=new
            )
        except:
            msg+=2
        try:
            stuchengji.objects.get_or_create(
                num=int(request.POST.get('xuehao')),
                xingming=request.POST.get('name'),
                kecheng=request.POST.get('kecheng1'),
                chuqin=int(request.POST.get('chuqin1', 100)),
                taidu=int(request.POST.get('taidu1', 100)),
                zuoye=int(request.POST.get('zuoye1', 0)),
                ceyan=int(request.POST.get('ceyan1', 0)),
                danyuan=int(request.POST.get('danyuan1', 0)),
                qizhong=int(request.POST.get('qizhong1', 0)),
                qimo=int(request.POST.get('qimo1', 0))
            )
            stuchengji.objects.get_or_create(
                num=int(request.POST.get('xuehao')),
                xingming=request.POST.get('name'),
                kecheng=request.POST.get('kecheng2'),
                chuqin=int(request.POST.get('chuqin2', 100)),
                taidu=int(request.POST.get('taidu2', 100)),
                zuoye=int(request.POST.get('zuoye2', 0)),
                ceyan=int(request.POST.get('ceyan2', 0)),
                danyuan=int(request.POST.get('danyuan2', 0)),
                qizhong=int(request.POST.get('qizhong2', 0)),
                qimo=int(request.POST.get('qimo2', 0))
            )
            stuchengji.objects.get_or_create(
                num=int(request.POST.get('xuehao')),
                xingming=request.POST.get('name'),
                kecheng=request.POST.get('kecheng3'),
                chuqin=int(request.POST.get('chuqin3', 100)),
                taidu=int(request.POST.get('taidu3', 100)),
                zuoye=int(request.POST.get('zuoye3', 0)),
                ceyan=int(request.POST.get('ceyan3', 0)),
                danyuan=int(request.POST.get('danyuan3', 0)),
                qizhong=int(request.POST.get('qizhong3', 0)),
                qimo=int(request.POST.get('qimo3', 0))
            )
            stuchengji.objects.get_or_create(
                num=int(request.POST.get('xuehao')),
                xingming=request.POST.get('name'),
                kecheng=request.POST.get('kecheng4'),
                chuqin=int(request.POST.get('chuqin4', 100)),
                taidu=int(request.POST.get('taidu4', 100)),
                zuoye=int(request.POST.get('zuoye4', 0)),
                ceyan=int(request.POST.get('ceyan4', 0)),
                danyuan=int(request.POST.get('danyuan4', 0)),
                qizhong=int(request.POST.get('qizhong4', 0)),
                qimo=int(request.POST.get('qimo4', 0))
            )
            stuchengji.objects.get_or_create(
                num=int(request.POST.get('xuehao')),
                xingming=request.POST.get('name'),
                kecheng=request.POST.get('kecheng5'),
                chuqin=int(request.POST.get('chuqin5', 100)),
                taidu=int(request.POST.get('taidu5', 100)),
                zuoye=int(request.POST.get('zuoye5', 0)),
                ceyan=int(request.POST.get('ceyan5', 0)),
                danyuan=int(request.POST.get('danyuan5', 0)),
                qizhong=int(request.POST.get('qizhong5', 0)),
                qimo=int(request.POST.get('qimo5', 0))
            )
            stuchengji.objects.get_or_create(
                num=int(request.POST.get('xuehao')),
                xingming=request.POST.get('name'),
                kecheng=request.POST.get('kecheng6'),
                chuqin=int(request.POST.get('chuqin6', 100)),
                taidu=int(request.POST.get('taidu6', 100)),
                zuoye=int(request.POST.get('zuoye6', 0)),
                ceyan=int(request.POST.get('ceyan6', 0)),
                danyuan=int(request.POST.get('danyuan6', 0)),
                qizhong=int(request.POST.get('qizhong6', 0)),
                qimo=int(request.POST.get('qimo6', 0))
            )
            stuchengji.objects.get_or_create(
                num=int(request.POST.get('xuehao')),
                xingming=request.POST.get('name'),
                kecheng=request.POST.get('kecheng7'),
                chuqin=int(request.POST.get('chuqin7', 100)),
                taidu=int(request.POST.get('taidu7', 100)),
                zuoye=int(request.POST.get('zuoye7', 0)),
                ceyan=int(request.POST.get('ceyan7', 0)),
                danyuan=int(request.POST.get('danyuan7', 0)),
                qizhong=int(request.POST.get('qizhong7', 0)),
                qimo=int(request.POST.get('qimo7', 0))
            )
        except:
            msg+=5
        context["msg"]=msg
        return render(request, "teacher/addstu.html", context)
    else:
        return render(request, "teacher/addstu.html", {})


def zuoye(request):
    return render(request, "teacher/zuoye.html", {})





def up(request):
    pathDir =  os.listdir('upload')
    fildlist=[]
    for allDir in pathDir:
        file=allDir .decode('gbk')
        fildlist.append(file)
    return render(request, "teacher/up.html",{'list':fildlist})
@csrf_exempt
def upload(request):
    if request.method == "POST":    # 请求方法为POST时，进行处理
        if request.GET.get('type')==0:
            myFile =request.FILES.get("myfile", None)    # 获取上传的文件，如果没有文件，则默认为None
            if not myFile:
                return HttpResponse("no files for upload!")
            destination = open(os.path.join("upload",myFile.name),'wb+')    # 打开特定的文件进行二进制的写操作
            for chunk in myFile.chunks():      # 分块写入文件
                destination.write(chunk)
            destination.close()
            return HttpResponse("upload over!")
        # if request.GET.get('type')==1:



def default(request):
    sdulist=user.objects.all()
    sdulist=sdulist.filter(type=0, group=context["g"],classname=context["c"])
    sdulist=sdulist.order_by('num').values("num", "name", "id_card", "phone","address")
    context["sdulist"]=sdulist
    return render(request, "teacher/submain.html", context)


def cakan(request):
    return

@csrf_exempt
def bianji(request):
    if request.method == 'GET':
        xuehao=request.GET.get('id')
        g=context["g"]
        c=context["c"]
        chengjilist=[]
        chengjilist=stuchengji.objects.filter(num=xuehao).query
        chengjilist.group_by=['kecheng']
        chengjilist = QuerySet(query=chengjilist, model=stuchengji)
        list=[]
        for chengji in chengjilist:
            list.append(chengji)
        context['count']=len( chengjilist)
        return render(request, "teacher/bianji.html",{'list':list})
    if request.method == 'POST':
        count = 0
        while (count < context['count']):
            countstr=str(count+1)
            count+=1
            id=request.POST.get(countstr)
            chuqin = request.POST.get('chuqin'+countstr)
            taidu =request.POST.get('taidu'+countstr)
            zuoye = request.POST.get('zuoye'+countstr)
            ceyan =request.POST.get('ceyan'+countstr)
            danyuan=request.POST.get('danyuan'+countstr)
            qizhong=request.POST.get('qizhong'+countstr)
            qimo=request.POST.get('qimo'+countstr)
            stuchengji.objects.filter(id=id).update(chuqin=chuqin,taidu=taidu,zuoye=zuoye,ceyan=ceyan,danyuan=danyuan,qizhong=qizhong,qimo=qimo)
        return HttpResponseRedirect("../def/")

def email(request):
    if request.method == 'GET':
        xuehao=request.GET.get('id')
        email=user.objects.values('num__email').filter(id_card=xuehao)
        emails=user.objects.values('num__email','name').filter(group=context["g"],classname=context["c"]).exclude(id_card=xuehao)
        list={}
        list['email']=email[0]['num__email']
        list['emails']=emails
        return render(request, "teacher/email.html",list)


def hudong(request):
    return render(request, "teacher/hudong.html", {})


def jiaowu(request):
    return render(request, "teacher/jiaowu.html", {})